package com.jsz.peini.common.util;

import java.net.URL;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import com.jsz.peini.bean.coupon.CouponUser;
import com.jsz.peini.bean.user.UserInfo;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

public class EhcacheUtil {
	
	private static final String path = "/ehcache.xml";  
	  
    private URL url;  
  
    private CacheManager manager;  
  
    private static EhcacheUtil ehCache;
    
    private EhcacheUtil(String path) {  
        url = getClass().getResource(path);  
        manager = CacheManager.create(url);  
    }  
  
    public static EhcacheUtil getInstance() {
        if (ehCache== null) {  
            ehCache= new EhcacheUtil(path);
        }  
        return ehCache;  
    }

    public void put(String cacheName, String key, Object value) {  
        Cache cache = manager.getCache(cacheName);  
        Element element = new Element(key, value);  
        cache.put(element);
    }  
  
    public Object get(String cacheName, String key) {  
        Cache cache = manager.getCache(cacheName);
        Element element = cache.get(key);  
        return element == null ? null : element.getObjectValue();  
    }  
  
    public Cache get(String cacheName) {  
        return manager.getCache(cacheName);  
    }  
  
    public void remove(String cacheName, String key) {  
        Cache cache = manager.getCache(cacheName);  
        cache.remove(key);  
    }
    
    //根据token返回userId
    public String getUserIdByToken(String token){
    	String result = "";
    	Cache cache = manager.getCache("userCache");
    	List<String> keys = cache.getKeys();
    	for (String key : keys) {  
            Element element = cache.get(key);
            if(((String)element.getObjectValue()).equals(token)){
            	result = key;
            	break;
            }
        }
    	return result;
    }

    public Integer getSignCnt(String userId){
    	Integer result = 0;
    	Cache cache = manager.getCache("userSignCache");
    	if(cache == null){
    		return result;
    	}else{
    		Element element = cache.get(userId);
    		if(element != null){
    			return (Integer)element.getObjectValue();
    		}else{
    			return 0;
    		}
    		
    	}
    }
    
    public void setSignCnt(String userId,int cnt){
    	Integer result = 0;
    	EhcacheUtil.getInstance().put("userSignCache", userId, cnt);
    }
}
